package com.example.com.netty.listen;

import com.example.com.netty.NettyConAddress;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author 杜豪波
 * @description: TODO
 * @date 2020/1/3 14:33
 */
public class NettyConnectListener {
    private static final Logger logger = LoggerFactory.getLogger(NettyConnectListener.class);
    //客户端重连3次后定时任务间隔时间
    public final static int MAX_SCHEDULE_INTERVAL=60;
    //初始的客户端重连定时任务间隔时间单位：秒
    public final static int MIN_SCHEDULE_INTERVAL=10;
    //重连次数到了3，重连的时间进行改变
    public final static int MAX_RECONN_NUM=3;
    //当前的客户端重连次数
    public static Integer currentReConnNum=1;

    public void operationComplete(ChannelFuture channelFuture, NettyConAddress address) throws Exception {

        //连接不成功的时候就启动线程一直尝试去连接
        if(!channelFuture.isSuccess()) {
            int intervalSeconds=currentReConnNum>MAX_RECONN_NUM?MAX_SCHEDULE_INTERVAL:MIN_SCHEDULE_INTERVAL;
            EventLoop eventLoop =channelFuture.channel().eventLoop();
            eventLoop.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("服务端连接不上，重新尝试连接...");
                    try {
                        //调用重连方法
                        currentReConnNum++;
                        NettyClientListen.reConnClient(address);
                    }catch (Exception e) {
                        e.printStackTrace();
                        logger.error("netty客户端重连失败");
                        //抛异常的时候也去重连
                        NettyClientListen.reConnClient(address);
                    }
                }
            }, intervalSeconds, TimeUnit.SECONDS);

        }else {
            currentReConnNum=1;
            System.out.print("服务端连接成功...");
        }
    }

}
